<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./lib.js"></script>
    <style>
        #tip {
            color: red;
            border: 1px solid #dddddd;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    
    <div id="content">
        <p id="tip">
            在数组输入框中输入数字，如1 2 4，点击求和，求出数组的和
        </p>
        数组：<input id="data" type="text" /><br />
        结果：<input id="result" type="text" /><br/>
        <button onclick="calSum()">求和！</button>
        <button onclick="average()">平均值！</button>
        <button onclick="median()">求中位数！</button>
    </div>

</body>
<script>
    // 全局变量，接受和承载数据
    var data = document.getElementById("data");
    var result = document.getElementById("result");

    function packData() {
        
        var array = data.value.split(' '); 
        return {
            array: array,
            length: array.length
        };
    }

    /** 
     * 求和
    */
    function calSum() {

        var data = packData();
        var array = data.array;
        var length = data.length;

        var sum = 0;

        for (let i = 0; i < length; i++) {
            sum += Number(array[i]);    
        }
        // 封装数据
        data['sum'] = sum;
        result.value = sum;
        return data;
    }

    function average() {
        
        var total = calSum();
        var ave = total.sum / total.length;
        // 封装数据
        total['average'] = ave;
        result.value = ave;
        return total;
    }

    function median() {

        var total = calSum();

        var median = 0;
        var index = Math.floor(total.length / 2);

        if ( isEven(total.length)) {
            median = (Number(total.array[index]) + Number(total.array[index-1])) / 2;
        } else {
            median = Number(total.array[index]);
        }
        total['median'] = median;
        result.value = median;
    }


</script>
</html>